package app

import (
	"fmt"
	"io"
	"runtime"
	"strings"

	"gitee.com/youkelike/ziam/zoptions"
	"github.com/moby/term"

	"github.com/spf13/cobra"
)

// type RunCommandFunc func(args []string) error

// type Command struct {
// 	usage    string
// 	desc     string
// 	options  CliOptions
// 	commands []*Command
// 	runFunc  RunCommandFunc
// }

// type CommandOption func(*Command)

// func WithCommandOptions(opts CliOptions) CommandOption {
// 	return func(c *Command) {
// 		c.options = opts
// 	}
// }

// func WithCommandFunc(run RunCommandFunc) CommandOption {
// 	return func(c *Command) {
// 		c.runFunc = run
// 	}
// }

// func NewCommand(usage, desc string, opts ...CommandOption) *Command {
// 	c := &Command{
// 		usage: usage,
// 		desc:  desc,
// 	}

// 	for _, o := range opts {
// 		o(c)
// 	}

// 	return c
// }

// func (c *Command) AddCommand(cmd *Command) {
// 	c.commands = append(c.commands, cmd)
// }

// func (c *Command) AddCommands(cmds ...*Command) {
// 	c.commands = append(c.commands, cmds...)
// }

// func (c *Command) cobraCommand() *cobra.Command {
// 	cmd := &cobra.Command{
// 		Use:   c.usage,
// 		Short: c.desc,
// 	}
// 	cmd.SetOutput(os.Stdout)
// 	cmd.Flags().SortFlags = false
// 	if len(c.commands) > 0 {
// 		for _, command := range c.commands {
// 			cmd.AddCommand(command.cobraCommand())
// 		}
// 	}

// 	if c.runFunc != nil {
// 		cmd.Run = c.runCommand
// 	}

// 	if c.options != nil {
// 		for _, f := range c.options.Flags().FlagSets {
// 			cmd.Flags().AddFlagSet(f)
// 		}
// 	}

// 	addHelpCommandFlag(c.usage, cmd.Flags())

// 	return cmd
// }

// func (c *Command) runCommand(cmd *cobra.Command, args []string) {
// 	if c.runFunc != nil {
// 		if err := c.runFunc(args); err != nil {
// 			fmt.Printf("%v %v\n", color.RedString("Error:"), err)
// 			os.Exit(1)
// 		}
// 	}
// }

func FormatBasename(basename string) string {
	if runtime.GOOS == "windows" {
		basename = strings.ToLower(basename)
		basename = strings.TrimSuffix(basename, ".exe")
	}

	return basename
}

func GetTerminalSize(w io.Writer) (int, int, error) {
	outFd, isTerminal := term.GetFdInfo(w)
	if !isTerminal {
		return 0, 0, fmt.Errorf("given writter is not a terminal")
	}

	winsize, err := term.GetWinsize(outFd)
	if err != nil {
		return 0, 0, err
	}

	return int(winsize.Width), int(winsize.Height), nil
}

func AddCmdTemplate(cmd *cobra.Command, nfs zoptions.NamedFlagSets) {
	// 设置帮助和示例
	usageFmt := "Usage:\n %s\n"
	cols, _, _ := GetTerminalSize(cmd.OutOrStdout())
	cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
		fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n"+usageFmt, cmd.Long, cmd.UseLine())
		// 格式化打印所有的命令组的提示
		zoptions.PrintSections(cmd.OutOrStdout(), nfs, cols)
	})
	cmd.SetUsageFunc(func(cmd *cobra.Command) error {
		fmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine())
		zoptions.PrintSections(cmd.OutOrStderr(), nfs, cols)
		return nil
	})
}
